// torrentScoring.js - 种子评分计算服务

/**
 * 计算技术维度评分 (30%)
 * @param {Object} stats - 种子统计数据，包含下载成功率和做种节点数
 * @returns {Number} - 技术维度评分 (0-100)
 */
const calculateTechnicalScore = (stats = {}) => {
  const { successRate = 0, seeders = 0 } = stats;

  // 1. 资源成功下载率 (50%)
  let downloadSuccessScore = 0;
  if (successRate >= 0.9) {
    downloadSuccessScore = 100;
  } else if (successRate <= 0.3) {
    downloadSuccessScore = 0;
  } else {
    // 在30%到90%之间线性计算
    downloadSuccessScore = ((successRate - 0.3) / 0.6) * 100;
  }

  // 2. 资源健康度 (50%)
  let healthScore = 0;
  if (seeders >= 50) {
    healthScore = 100;
  } else if (seeders <= 10) {
    healthScore = Math.max((seeders / 10) * 50, 0); // 10节点以下，最高50分
  } else {
    // 在10到50之间线性计算
    healthScore = 50 + ((seeders - 10) / 40) * 50;
  }

  // 加权平均
  return downloadSuccessScore * 0.5 + healthScore * 0.5;
};

/**
 * 计算内容维度评分 (50%)
 * @param {Object} ratings - 评分数据，包含平均分和评分数量
 * @returns {Number} - 内容维度评分 (0-100)
 */
const calculateContentScore = (ratings = {}) => {
  const { avgScore = 0, count = 0 } = ratings;

  // 用户评分转换为0-100分制
  return avgScore * 20; // 将5分制转换为100分制
};

/**
 * 计算社区维度评分 (20%)
 * @param {Object} communityData - 社区数据，包含响应时间和长期价值
 * @returns {Number} - 社区维度评分 (0-100)
 */
const calculateCommunityScore = (communityData = {}) => {
  const {
    responseTime = 48,
    discussions = 0,
    updates = 0,
    age = 1,
  } = communityData;

  // 1. 问题响应时间 (50%)
  let responseScore = 0;
  if (responseTime <= 12) {
    responseScore = 100;
  } else if (responseTime >= 48) {
    responseScore = 30;
  } else {
    // 在12到48小时之间线性计算
    responseScore = 100 - ((responseTime - 12) / 36) * 70;
  }

  // 2. 长期价值系数 (50%)
  // 计算因素：讨论量、更新次数、年龄（天）
  const discussionFactor = Math.min(discussions / 20, 1); // 每20条讨论满分
  const updateFactor = Math.min(updates / 5, 1); // 每5次更新满分
  const ageFactor = Math.min(age / 180, 1); // 半年内逐渐增加权重

  const longTermValue =
    (discussionFactor * 0.4 + updateFactor * 0.4 + ageFactor * 0.2) * 100;

  // 加权平均
  return responseScore * 0.5 + longTermValue * 0.5;
};

/**
 * 使用贝叶斯平均修正评分
 * @param {Number} score - 原始评分
 * @param {Number} count - 评分数量
 * @param {Number} prior - 先验评分
 * @param {Number} weight - 先验权重
 * @returns {Number} - 修正后的评分
 */
const bayesianAverage = (score, count, prior = 40, weight = 10) => {
  if (count === 0) return prior;
  return (weight * prior + count * score) / (weight + count);
};

/**
 * 计算总体评分
 * @param {Object} torrentData - 种子数据，包含所有评分维度的原始数据
 * @returns {Object} - 详细的评分结果
 */
const calculateTorrentScore = (torrentData) => {
  const {
    stats = {},
    ratings = { avgScore: 0, count: 0 },
    communityData = {},
  } = torrentData;

  // 计算三个维度的原始分数
  const technicalScore = calculateTechnicalScore(stats);
  const contentScore = calculateContentScore(ratings);
  const communityScore = calculateCommunityScore(communityData);

  // 加权计算总分 (技术30%，内容50%，社区20%)
  const rawScore =
    technicalScore * 0.3 + contentScore * 0.5 + communityScore * 0.2;

  // 贝叶斯平均修正 (使用评分次数作为可信度)
  const totalCount = ratings.count || 0;
  const finalScore = bayesianAverage(rawScore, totalCount);

  return {
    finalScore: parseFloat(finalScore.toFixed(1)),
    technicalScore: parseFloat(technicalScore.toFixed(1)),
    contentScore: parseFloat(contentScore.toFixed(1)),
    communityScore: parseFloat(communityScore.toFixed(1)),
    components: {
      technical: {
        successRate: stats.successRate || 0,
        seeders: stats.seeders || 0,
      },
      content: {
        avgRating: ratings.avgScore || 0,
        ratingsCount: ratings.count || 0,
      },
      community: {
        responseTime: communityData.responseTime || 0,
        discussions: communityData.discussions || 0,
        updates: communityData.updates || 0,
        age: communityData.age || 0,
      },
    },
    reliability: Math.min(totalCount / 20, 1), // 可靠度指标，最高1
  };
};

module.exports = {
  calculateTorrentScore,
  calculateTechnicalScore,
  calculateContentScore,
  calculateCommunityScore,
  bayesianAverage,
};
